﻿using System;
using System.Configuration;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.DirectoryServices;
using System.Collections;
using System.Collections.Generic;

namespace InfoLeech
{
    public partial class ctlADtools : UserControl
    {
        private string filter;
        private string Base;
        private string Field;
        private string searchAttributes;
        private byte minSearchStringLength = 3;
        private Dictionary<string, string> domainlist = frmMain.domainlist;

        public ctlADtools()
        {
            InitializeComponent();
            cbClass.SelectedIndex = 0;
        }
        private void btnSearch_Click(object sender, EventArgs e)
        {
            startSearch();
        }
        private void enterKeyPressed(Object o, KeyPressEventArgs e)
        {
            // The keypressed method uses the KeyChar property to check 
            // whether the ENTER key is pressed. 

            if (e.KeyChar == (char)Keys.Return)
            {
                startSearch();
            }
        }
        private void cbClass_SelectedIndexChanged(object sender, EventArgs e)

        {
            if (cbClass.SelectedItem.ToString() == "COMPUTER" | cbClass.SelectedItem.ToString() == "PRINTQUEUE")
                cbLocationField.Enabled = true;
            else
                cbLocationField.Enabled = false;
        }
        private void startSearch()
        {
            // form the filter string for directory search
            if (tbSearchString.Text.Length < minSearchStringLength)
            {
                MessageBox.Show("De zoekstring moet minimaal " + minSearchStringLength + " karakters lang zijn!");
                return;
            }

            // set the ldap base, depending on the selected domain
            if (domainlist.ContainsKey(cbDomain.SelectedItem.ToString()))
            {
                Base = domainlist[cbDomain.SelectedItem.ToString()];
            }

            if (cbClass.SelectedItem.ToString() == "COMPUTER" | cbClass.SelectedItem.ToString() == "PRINTQUEUE")
            {
                if (cbLocationField.Checked)
                {
                    filter = "(&(objectCategory=" + cbClass.SelectedItem.ToString() + ")(|(CN=*" +
                        tbSearchString.Text + "*)(location=*" + tbSearchString.Text + "*)))";
                    Field = "Location";
                }
                else
                {
                    filter = "(&(objectCategory=" + cbClass.SelectedItem.ToString() + ")(|(CN=*" +
                        tbSearchString.Text + "*)(description=*" + tbSearchString.Text + "*)))";
                    Field = "Description";
                }
            }
            else
            {
                filter = "(&(objectCategory=" + cbClass.SelectedItem.ToString() + ")(|(CN=*" + tbSearchString.Text +
                    "*)(description=*" + tbSearchString.Text + "*)(sAMAccountName=*" + tbSearchString.Text + "*)))";
                Field = "Description";
            }

            searchAttributes = "sAMAccountName,cn,distinguishedName," + Field;

            // Instantiate directory searcher object.
            DirectorySearcher adsearch = new DirectorySearcher();
            adsearch.SearchRoot = new DirectoryEntry(Base);
            adsearch.Filter = filter;
            adsearch.PropertyNamesOnly = true;
            adsearch.PropertiesToLoad.Add(searchAttributes);

            //Create datatable and add columns.
            DataTable tableResults = new DataTable();
            DataColumn sAMAccountNameColumn = new DataColumn("Account", typeof(string));
            DataColumn cnameColumn = new DataColumn("Common Name", typeof(string));
            DataColumn dnameColumn = new DataColumn("Distinguished Name", typeof(string));
            DataColumn descriptionColumn = new DataColumn(Field, typeof(string));
            tableResults.Columns.AddRange(new DataColumn[] { sAMAccountNameColumn, cnameColumn, dnameColumn, descriptionColumn });

            try
            {
                // Start searching...
                SearchResultCollection result = adsearch.FindAll();

                // Fill datatable with search results.
                foreach (SearchResult sr in result)
                {
                    DataRow rw = tableResults.NewRow();
                    DirectoryEntry de = sr.GetDirectoryEntry();
                    rw[sAMAccountNameColumn] = de.Properties["sAMAccountName"].Value;
                    rw[cnameColumn] = de.Properties["cn"].Value;
                    rw[dnameColumn] = de.Properties["distinguishedName"].Value;
                    rw[descriptionColumn] = de.Properties[Field].Value;
                    tableResults.Rows.Add(rw);
                    de.Close();
                }

                // set the grid's data source
                dataGridViewResult.DataSource = tableResults;
            }

            catch (Exception e)
            {
                MessageBox.Show(e.Message);
            }

            adsearch.Dispose();
        }

        private void copyToolStripMenuItem_Click(object sender, EventArgs e)
        {
            // The context menu strip called this method, so we need to determine which DGV it was clicked on    
            ToolStripDropDownItem item = sender as ToolStripDropDownItem;
            if (item == null) // Error            
                return;
            ContextMenuStrip strip = item.Owner as ContextMenuStrip;
            DataGridView grid = strip.SourceControl as DataGridView;
            if (grid == null) // Control wasn't a DGV
                return;
            DataObject data = grid.GetClipboardContent();
            if (data != null)
                Clipboard.SetDataObject(data);
        }

        private void selectAllToolStripMenuItem_Click(object sender, EventArgs e)
        {
            // The context menu strip called this method, so we need to determine which DGV it was clicked on    
            ToolStripDropDownItem item = sender as ToolStripDropDownItem;
            if (item == null) // Error            
                return;
            ContextMenuStrip strip = item.Owner as ContextMenuStrip;
            DataGridView grid = strip.SourceControl as DataGridView;
            if (grid == null) // Control wasn't a DGV
                return;
            grid.SelectAll();
        }

        // read the domainlist from settingsfile and fill combobox cbDomain
        public void fillDomainListbox()
        {
            // add domain to arraylist
            ArrayList items = new ArrayList(domainlist.Keys);
            items.Sort();
            // add domainlist to cbDomain
            this.cbDomain.Items.AddRange(items.ToArray());
            cbDomain.SelectedIndex = 0;
        }
    }
}
